package com.ym.core.utils;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import com.ym.core.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @Author wenbo
 * @Date 2020/2/10 13:08
 **/
public class ImportJsonUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(ImportJsonUtil.class);

	public static JSONObject jsonFile(MultipartFile jsonFile) {
		InputStream in = null;
		String line = "";
		StringBuilder jsonString = new StringBuilder();
		BufferedReader reader = null;
		try {
			in = jsonFile.getInputStream();
			reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
			while ((line = reader.readLine()) != null) {
				jsonString.append(line);
			}
		} catch (Exception e) {
			if (e instanceof IOException) {
				LOGGER.info("json导入流 异常 {}", e.getMessage());
			}
			if (e instanceof JSONException) {
				throw new BusinessException("请检查json格式是否正确!");
			}
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				LOGGER.info("json导入关闭流 异常 {}", e.getMessage());
			}
		}
		JSONObject jsonObject = null;
		try {
			jsonObject = JSONObject.parseObject(jsonString.toString());
		} catch (Exception e) {
			if (e instanceof JSONException) {
				throw new BusinessException("请检查json格式是否正确!");
			}
			e.printStackTrace();
		}
		return jsonObject;
	}

}
